<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
      multiple
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <div>
      图片上传功能,当前用的是腾讯云的存储桶,需要把自己存储桶的id与key用上才能使用
    </div>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: '', //这两项是腾讯云的存储桶的id与key

  SecretKey: ''
})
console.log(cos)
export default {
  data () {
    return {
      show: true,
      imageUrl: '',
      cos: '',
      list: []
    }
  },

  methods: {
    llll () {
      console.log(this.list)
    },
    beforeAvatarUpload (file) {
      console.log('file', file)
      const typeArr = ['image/jpeg', 'image/png']
      const typeBol = typeArr.includes(file.type)
      if (!typeBol) {
        this.$message.error('请上传jpg与png图片')
      }
      const limit1m = file.size / 1024 / 1024 < 5
      if (!limit1m) {
        this.$message.error('只允许1mb的图片')
      }
      return typeBol && limit1m
    },
    httpRequest (res) {
      cos.uploadFile(
        {
          Bucket: '2426328536-1316373723',
          Region: 'ap-guangzhou',
          Key: res.file.name,
          Body: res.file,
          SliceSize: 1024 * 1024 * 5,
          onProgress: data => {
            console.log(data)
          }
        },
        (err, data) => {
          this.list.push('http://' + data.Location)
          console.log('data', data)
          if (!err) {
            this.imageUrl = 'http://' + data.Location
          }
        }
      )
    },
    handleClose (str) {
      this.$confirm('确认关闭吗')
        .then(() => {
          str()
          console.log(str)
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
